﻿using AutoMapper;
using Chat.EntityFrameworkCore;
using Cx.NetCoreUtils.Exceptions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xiao.Code.DbEnum;
using Xiao.Code.Entities.User;
using Xiao.Code.Entities.Users;
using Xiao.EntityFrameworkCore.Core;
using Xiao.EntityFrameworkCore.Repository;

namespace Xiao.Application.Services.User
{
    public interface IConsumerService
    {
        Task<ConsumerDto> GetConsumer(string user,string pass);
        Task<Guid> CreateConsumer(ConsumerDto consumer);
        /// <summary>
        /// 获取好友基本信息
        /// </summary>
        /// <param name="frendId"></param>
        /// <returns></returns>
        Task<ConsumerDto> GetFrend(Guid frendId);
        Task<ConsumerDto> GetUser(string user);
    }
    public class ConsumerService : BaseService<Consumer>, IConsumerService
    {
        private readonly IMapper _mapper;
        public ConsumerService
            (IMapper mapper,
            IUnitOfWork<MasterDbContext> unitOfWork,
            IMasterDbRepositoryBase<Consumer> currentRepository)
            : base(unitOfWork, currentRepository)
        {
            _mapper = mapper;
        }

        public async Task<Guid> CreateConsumer(ConsumerDto consumer)
        {
            if (currentRepository.FindAll(a => a.UserNumber == consumer.UserNumber).Any()) throw new BusinessLogicException("账号已经存在");
            consumer.Status = StatusEnum.Start;
            var user = _mapper.Map<Consumer>(consumer);
            user = currentRepository.Add(user);
            await unitOfWork.SaveChangesAsync();
            return user.Id;
        }

        public async Task<ConsumerDto> GetConsumer(string user, string pass)
        {
            var data=await currentRepository.FindAll(a=>a.UserNumber==user&&a.PassWord==pass)
                .AsNoTracking()
                .FirstOrDefaultAsync();
            if (data == null) throw new BusinessLogicException("账号或者密码错误");
            return _mapper.Map<ConsumerDto>(data);
        }

        public async Task<ConsumerDto> GetFrend(Guid frendId)
        {
            var user =await currentRepository.FindAll(a => a.Id == frendId).FirstOrDefaultAsync();
            if (user == null) throw new BusinessLogicException("好友不存在");
            user.PassWord = "";
            return _mapper.Map<ConsumerDto>(user);
        }

        public async Task<ConsumerDto> GetUser(string userNumber)
        {
            var data=await currentRepository.FindAll(a=>a.UserNumber == userNumber).FirstOrDefaultAsync();
            if (data == null) throw new BusinessLogicException("账号不存在");
            data.PassWord = "";
            return _mapper.Map<ConsumerDto>(data);
        }
    }
}
